//
//  ContactsViewController.m
//  SIPphone
//
//  Created by wrt on 13-10-25.
//  Copyright (c) 2013年 wrtsoft. All rights reserved.
//  联系人

#import "ContactsViewController.h"
#import "AddContactsViewController.h"
#import "MyChineseBookAddress.h"
#import "ContactsDateBase.h"
#import "ContactsDetailViewController.h"

@interface ContactsViewController ()
{
    //从数据库中读出来的暂存的字符串
    NSString *tempUserName;
    NSString *tempDisplayName;
    NSString *tempMarkName;
    NSString *tempIpPort;
    NSString *tempOnlinestatus;
    NSString *tempIsFriend;
}

@end

@implementation ContactsViewController

@synthesize tableView = _tableView, m_allName = _m_allName;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = NSLocalizedString(@"contact", @" 联系人 tabbar Item For contact name ");
    }
    return self;
}

//界面出现时就要刷新表格的内容
- (void)viewWillAppear:(BOOL)animated
{
    ContactsDateBase *contactsBD = [ContactsDateBase shareContactsDataBase];
    //用数据库赋值
    [contactsBD readDB];
    //对联系人进行拼音排序处理
    [self pinyinMethod];
    //刷新表格
    [self.tableView reloadData];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    ContactsDateBase *contactsBD = [ContactsDateBase shareContactsDataBase];
    //用数据库赋值
    [contactsBD readDB];
    
    //对联系人进行拼音排序处理
    [self pinyinMethod];
    
    //将添加联系人的按钮 放置在导航栏的右上角
//    UIBarButtonItem *addContactsButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(pushAddcontacts)];
    UIBarButtonItem *addContactsButton = [[UIBarButtonItem alloc] initWithTitle:@"十" style:UIBarButtonItemStylePlain target:self action:@selector(pushAddcontacts)];
//    UIBarButtonItem *addContactsButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"+.png"] style:UIBarButtonItemStylePlain target:self action:@selector(pushAddcontacts)];
    
    self.navigationItem.rightBarButtonItem = addContactsButton;
    
    //初始化暂存数组
    tempUserName = [[NSString alloc] init];
    tempDisplayName = [[NSString alloc] init];
    tempMarkName = [[NSString alloc] init];
    tempIpPort = [[NSString alloc] init];
    tempOnlinestatus = [[NSString alloc] init];
    tempIsFriend = [[NSString alloc] init];
    
    //设置通知来刷新界面
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadtableView) name:@"RELOADTABLEVIEWNOTICE" object:nil];
    
}

//对联系人的拼音处理
- (void)pinyinMethod
{
    
    ContactsDateBase *contactsBD = [ContactsDateBase shareContactsDataBase];
    //获取全部的姓名
    dataSouceArray = [NSArray arrayWithArray:contactsBD.markNameArray];
    self.m_allName = [[NSMutableArray alloc] init];
    for (int i=0; i<dataSouceArray.count; i++)
    {
        //获取他的第一个汉字
        char firstChar = pinyinFirstLetter([[dataSouceArray objectAtIndex:i] characterAtIndex:0]);
        NSString *youName = [NSString stringWithFormat:@"%c",firstChar];
        //不添加重复元素
        if (![_m_allName containsObject:[youName uppercaseString]])
        {
            [self.m_allName addObject:[youName uppercaseString]];
        }
    }
    //排序
    [self.m_allName sortUsingSelector:@selector(compare:)];
    nameDic = [[NSMutableDictionary alloc] init];
    //每个section对应的行数列表
    for(NSString *sectionString  in _m_allName)
    {
        NSMutableArray *rowSource = [[NSMutableArray alloc] init];
        for (NSString *charString in dataSouceArray)
        {
            char firstChar = pinyinFirstLetter([charString characterAtIndex:0]);
            NSString *youName = [NSString stringWithFormat:@"%c",firstChar];
            if ([sectionString isEqualToString:[youName uppercaseString]]) {
                [rowSource addObject:charString];
            }
        }
        [nameDic setValue:rowSource forKey:sectionString];
    }
}

//跳转到添加联系人的方法
- (void)pushAddcontacts
{
    AddContactsViewController *addContactVC = [[AddContactsViewController alloc] init];
    [addContactVC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:addContactVC animated:YES];
}

#pragma mark -
#pragma mark tableViewDelegateMethod
//返回字典中的对应的姓的数量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *dicCount = [nameDic objectForKey:[self.m_allName objectAtIndex:section]];
    return [dicCount count];
}

//返回section的数量
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.m_allName count];
}

//section的标题
- (NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [self.m_allName objectAtIndex:section];
}

//返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ContactsDateBase *contactsBD = [ContactsDateBase shareContactsDataBase];
    static NSString *cellId = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
    }
    
    NSString * sectionString = [self.m_allName objectAtIndex:indexPath.section];
    NSArray *allShowName = [nameDic objectForKey:sectionString];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 34, 34)];
    imageView.image = [UIImage imageNamed:@"app_panel_friendcard_icon.png"];
    [cell addSubview:imageView];
    
    
    if (allShowName.count>0)
    {
        cell.textLabel.text = [NSString stringWithFormat:@"       %@",[allShowName objectAtIndex:indexPath.row]];
        for (int i = 0 ; i < contactsBD.markNameArray.count; i++)
        {
            if ([contactsBD.markNameArray[i] isEqualToString:[allShowName objectAtIndex:indexPath.row]])
            {
                tempIsFriend = contactsBD.isFriendArray[i];
                if ([tempIsFriend isEqualToString:@"好友"])
                {
                    tempOnlinestatus = contactsBD.onlineStatusArray[i];
                    tempUserName = contactsBD.userNameArray[i];
//                    cell.detailTextLabel.text = [NSString stringWithFormat:@"         [%@] %@",tempOnlinestatus, tempUserName];
                    cell.detailTextLabel.text = [NSString stringWithFormat:@"         %@",tempUserName];
                }
                else
                {
                    tempUserName = contactsBD.userNameArray[i];
//                    cell.detailTextLabel.text = [NSString stringWithFormat:@"         [对方还未添加您为好友] %@",tempUserName];
                    cell.detailTextLabel.text = [NSString stringWithFormat:@"         %@",tempUserName];
                }
                
                
                break;
            }
        }
        
    }
    return cell;
}

//右侧的首字母搜索
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    NSInteger count = 0;
    for(NSString *character in self.m_allName)
    {
        if([character isEqualToString:title]) return count;
        count ++;
    }
    return 0;
}

//右侧的首字母搜索
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    NSMutableArray *toBeReturned = [[NSMutableArray alloc] init];
    for(char c = 'A';c<='Z';c++)
    [toBeReturned addObject:[NSString stringWithFormat:@"%c",c]];
    return toBeReturned;
}

//点击后的操作
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * sectionString = [self.m_allName objectAtIndex:indexPath.section];
    NSArray *allShowName = [nameDic objectForKey:sectionString];
    NSLog(@"%@",[allShowName objectAtIndex:indexPath.row]);
    
    ContactsDateBase *contactsBD = [ContactsDateBase shareContactsDataBase];
    for (int i = 0 ; i < contactsBD.markNameArray.count; i++)
    {
        if ([[allShowName objectAtIndex:indexPath.row] isEqualToString:contactsBD.markNameArray[i]])
        {
            tempUserName = contactsBD.userNameArray[i];
            tempDisplayName = contactsBD.displayNameArray[i];
            tempMarkName = contactsBD.markNameArray[i];
            tempIpPort = contactsBD.ipPortArray[i];
            tempIsFriend = contactsBD.isFriendArray[i];
            tempOnlinestatus = contactsBD.onlineStatusArray[i];
            break;
        }
    }
    ContactsDetailViewController *contactsDetailVC = [[ContactsDetailViewController alloc] initWithUserName:tempUserName andDisplayName:tempDisplayName andStatus:tempOnlinestatus andMarkName:tempMarkName andIP:tempIpPort andIsFriend:tempIsFriend];
    [contactsDetailVC setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:contactsDetailVC animated:YES];
}

- (void)reloadtableView
{
    dispatch_async(dispatch_get_main_queue(),^{
    [self performSelector:@selector(reloadtableViewDelay) withObject:nil afterDelay:1];
    });
}

- (void)reloadtableViewDelay
{
    //对联系人进行拼音排序处理
    [self pinyinMethod];
    //刷新表格
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    //Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"RELOADTABLEVIEWNOTICE" object:nil];
}


@end
